namespace Brjnk.GpxExplorer.WPF
{
    using System;
    using System.ComponentModel;
    using System.Windows.Data;

    /// <summary>
    /// </summary>
    public class MultiConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values.Length == 0 || (object)values[0] == null) return null;
            var converter = TypeDescriptor.GetConverter(values[0].GetType());
            if (converter.CanConvertTo(targetType))
            {
                return converter.ConvertTo(values[0], targetType);
            }
            return values[0];
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            object[] retVals = new object[targetTypes.Length];
            for (int i = 0; i < targetTypes.Length; i++)
            {
                var target = targetTypes[i];
                var converter = TypeDescriptor.GetConverter(target);
                if (converter.CanConvertFrom(value.GetType()))
                    retVals[i] = converter.ConvertFrom(value);
                else retVals[i] = GetDefaultValue(target);
            }
            return retVals;
        }

        public object GetDefaultValue(Type type)
        {
            return type.IsValueType ? Activator.CreateInstance(type) : null;
        }
    }
}